<template>
  <div class="dept-manage">
    <div class="query-form">
      <el-form :inline="true" :model="quForm" ref="queryForm">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="quForm.menuName" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">创建</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <el-table :data="menuList" row-key="menuId" border @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="item in columns" :prop="item.prop" :label="item.label" :width="item.width"
          :key="item.prop" :formatter="item.formatter">
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" size="small" @click="handleCreate(scope.row)"
              v-show="scope.row.menuType !== 3">创建</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 编辑弹窗 -->
    <el-dialog v-model="showEditDialog" title="创建机构" width="500px" center>
      <el-form :model="editMenu" ref="editForm" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="上级菜单" prop="parentId">
          <el-input v-model="editMenu.parentId" disabled />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="editMenu.menuName" />
        </el-form-item>
        <el-form-item label="标识" prop="perms">
          <el-input v-model="editMenu.perms" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="editMenu.menuType">
            <el-option label="请选择" :value="0"></el-option>
            <el-option label="目录" :value="1"></el-option>
            <el-option label="菜单" :value="2"></el-option>
            <el-option label="按钮" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="editMenu.url" />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNum">
          <el-input v-model="editMenu.orderNum"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 创建弹窗 -->
    <el-dialog v-model="showCreateDialog" title="创建机构" width="500px" center>
      <el-form :model="createMenu" ref="createForm" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="上级菜单" prop="parentId">
          <el-input v-model="createMenu.parentId" disabled />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="createMenu.menuName" />
        </el-form-item>
        <el-form-item label="标识" prop="perms">
          <el-input v-model="createMenu.perms" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="createMenu.menuType">
            <el-option label="请选择" :value="0"></el-option>
            <el-option label="目录" :value="1"></el-option>
            <el-option label="菜单" :value="2"></el-option>
            <el-option label="按钮" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="createMenu.url" />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNum">
          <el-input v-model="createMenu.orderNum"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import api from '@/api'
import { nextTick, onMounted, reactive, ref } from 'vue';
import { getCurrentInstance } from 'vue';
import { mapActions, mapState, mapWritableState, storeToRefs } from 'pinia';
import useMenuStore from '@/store/useMenuStore';
// 创建菜单实例
const menuStore = useMenuStore()

// 查询条件
const quForm = reactive({
  menuName: '',
})
// 表格列
const columns = [
  {
    label: "菜单",
    prop: "menuName",
    width: 180,
  },
  {
    label: "标识",
    prop: "perms",

  },

  {
    label: "URL",
    prop: "url",
    width: 200,
  },
  {
    label: "排序号",
    prop: "orderNum",
    width: 100,
  }
]
// 当前实例
const { proxy } = getCurrentInstance()
// 菜单列表
const menuList = ref([])
// 调用接口获取菜单列表
onMounted(() => {
  if (menuStore.menuList) {
    menuList.value = menuStore.menuList
  } else {
    getMenuList()
  }

})
// 编辑弹窗
const showEditDialog = ref(false)
// 创建弹窗
const showCreateDialog = ref(false)
// 删除弹窗
// const showDeleteDialog = ref(false)

// 删除菜单列表ID
const deleteMenuIds = ref([])
// 编辑菜单
const editMenu = ref({
  menuId: 1,
  menuName: '',
  parentId: 0,
  url: '',
  menuType: 0,
  orderNum: 1,
  perms: ''
})
// 创建
const createMenu = ref({
  menuName: '',
  parentId: 0,
  url: '',
  menuType: 0,
  orderNum: 1,
  perms: ''
})
// 表单校验
const rules = reactive({
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  url: [
    { required: true, message: '请输入url', trigger: 'blur' },
  ],
  perms: [
    { required: true, message: '请输入标识', trigger: 'blur' },
  ],
  orderNum: [
    { required: true, message: '请选择排序号', trigger: 'blur' },
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'blur' },
  ],
})
// 批量删除
const handleBatchDelete = async () => {
  if (deleteMenuIds.value.length > 0) {
    if (confirm('确定删除吗?')) {
      let res = await api.deleteMenu({ menuIds: [...deleteMenuIds.value] })
      if (res > 0) {
        proxy.$message.success('删除成功');
        deleteMenuIds.value = []
        getMenuList()
      } else {
        proxy.$message.fail('删除失败');
      }

    }
  }
}
const handleSelectionChange = (vals) => {
  let arr = []
  vals.forEach(element => {
    arr.push(element.menuId)
  });
  deleteMenuIds.value = arr
}
// 获取部门列表
const getMenuList = async () => {
  try {
    let data = await api.getPermissionList()
    menuStore.setMenuList(data)
    menuList.value = data
  } catch (err) {
    console.log(err);
  }
}
// 查询部门
const handleQuery = async () => {
  try {
    let data = await api.getMenuQuery({ ...quForm })
    if (data) {
      menuList.value = data
      proxy.$message.success('查询成功')
    } else {
      proxy.$message.fail('查询失败')
    }
    handleReset('queryForm')
  } catch (err) {
    console.log(err);
  }
}
// 重置查询条件
const handleReset = (formName) => {
  proxy.$refs[formName].resetFields()
}
// 递归获取菜单id
const depth = (list, data) => {
  if (data.length === 0) return
  data.forEach(item => {
    list.push(item.menuId)
    if (item.children) {
      depth(list, item.children)
    }
  })
}
// 删除菜单
const handleDelete = async (row) => {
  try {
    deleteMenuIds.value = [row.menuId]
    let list = []
    row.children && depth(list, row.children)
    if (confirm('确定删除该部门吗？')) {
      await api.deleteMenu({ menuIds: [...deleteMenuIds.value, ...list] })
      proxy.$message.success('删除成功')
      deleteMenuIds.value = []
      getMenuList()
    }
  } catch (err) {
    console.log(err);
  }
}

// 编辑菜单
const handleEdit = async (row) => {
  showEditDialog.value = true
  nextTick(() => {
    if (row) {
      editMenu.value.menuId = row.menuId
      editMenu.value.menuName = row.menuName
      editMenu.value.url = row.url
      editMenu.value.menuType = row.menuType
      editMenu.value.parentId = row.parentId
      editMenu.value.orderNum = row.orderNum
      editMenu.value.perms = row.perms
    }
  })
}
// 创建菜单
const handleCreate = async (row) => {
  showCreateDialog.value = true
  if (row.children) {
    nextTick(() => {
      createMenu.value.parentId = row.menuId
    })
  }
}
// 编辑确认
const handleEditConfirm = () => {
  proxy.$refs.editForm.validate(async (valid) => {
    if (!valid) return
    try {
      console.log('--------------->menu');
      let data = await api.updateMenu({ ...editMenu.value })
      if (data > 0) {
        showEditDialog.value = false
        proxy.$message.success('修改成功')
        handleReset('editForm')
        getMenuList()
      } else {
        proxy.$message.error('修改失败')
      }
    } catch (err) {
      console.log(err);
    }
  })
}
// 创建确认
const handleCreateConfirm = () => {
  proxy.$refs.createForm.validate(async (valid) => {
    if (!valid) return
    try {
      let res = await api.addMenu({ ...createMenu.value })
      if (res > 0) {
        showCreateDialog.value = false
        proxy.$message.success('添加成功')
        handleReset('createForm')
        getMenuList()
      } else {
        proxy.$message.error('创建失败')
      }
    } catch (err) {
      console.log(err);
    }
  })
}

</script>
<style lang="scss" scoped>
.dept-manage {
  height: 100%;
  overflow-y: scroll;
}

.query-form {
  display: flex;
  align-items: center;
  background: #fff;
  padding-top: 18px;
  margin-bottom: 16px;
  padding-left: 20px;
  border-radius: 4px;
}

.base-table {
  background: #fff;
  border-radius: 4px;

  .action {
    padding: 15px;
    border-bottom: 1px solid #eee;
  }
}
</style>

